﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class BusInformationRequester : SingletonMonoBehaviour<BusInformationRequester> 
{
	private SimpleJSON.JSONNode mainNode { get; set; }
	public float lastUpdateTime { get; private set; }
	public List<BusInformationModel> busInformation { get; private set; }

	[SerializeField]
	private GUIText text;

	protected override void Begin ()
	{
		base.Begin ();
		lastUpdateTime = -99999f;
	}

	public void DoRequest()
	{
		lastUpdateTime = Time.time;
		StopAllCoroutines();
		StartCoroutine(ExecuteService());
	}

	private IEnumerator ExecuteService()
	{
		WWW www = new WWW(Global.URL_BUS_SERVICE);
		yield return www;
		if(string.IsNullOrEmpty(www.error))
		{
			text.text = www.text;
			ReadData(www.text);
		}
		else
		{
			text.text = www.error.Replace(" ", "\n").Replace(".cfm", ".cfm\n");
			Debug.LogError("Ocorreu um erro ao consumir o servico das informacoes dos onibus \nError:" + www.error);
		}
		www.Dispose();
	}

	private void ReadData(string data)
	{
		//tive que fazer isso pro SimpleJSON funcionar
		data = data.Replace("\"\"", "\"null\"");

		mainNode = SimpleJSON.JSONNode.Parse(data);
		SimpleJSON.JSONNode dataNode = mainNode["DATA"];

		int length = dataNode.Count;
		Debug.Log("quantidade de onibus: " + length);

		if(busInformation != null)
			busInformation.Clear();
		else
			busInformation = new List<BusInformationModel>();

		for (int i = 0; i < length; i++) 
		{
			BusInformationModel currentInfo = new BusInformationModel(dataNode[i].AsArray);
			if(currentInfo.isValid) {
				busInformation.Add(currentInfo);
			}
		}

		TestBusService.loaded = true;
	}

	public List<BusInformationModel> FilterByLine(string line)
	{
		List<BusInformationModel> result = new List<BusInformationModel>();
		busInformation.ForEach
		( 
			delegate(BusInformationModel model) 
           	{
				if(model.line.ToUpper() == line.ToUpper()) {
					result.Add(model); 
				}
			}
		);
		return result;
	}
}
